package com.example.consumptionrecords.config.shiro;

import com.example.consumptionrecords.entity.enums.GlobalConstants;
import com.example.consumptionrecords.entity.pojo.User;
import com.example.consumptionrecords.mapper.PermissionMapper;
import com.example.consumptionrecords.mapper.RoleMapper;
import com.example.consumptionrecords.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Set;

/**
 * 孙敬佳
 * 2024 \ 02 \ 25
 */

public class UserRealm extends AuthorizingRealm {

//	@Override
//	public boolean supports(AuthenticationToken token) {
//
//	}

	@Resource
	private UserMapper userMapper;

	@Resource
	private PermissionMapper permissionMapper;

	@Resource
	private RoleMapper roleMapper;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		System.out.println("授权");
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		Integer userId = userMapper.selectUserByUsernameOrPhone(username).getId();
		Set<String> permissions = permissionMapper.selectUserPermission(userId);
		Set<String> roles = roleMapper.userRole(userId);

		info.setRoles(roles);
		info.setStringPermissions(permissions);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		System.out.println("认证");
		// 判断当前的登录方式
		if (authenticationToken instanceof UsernamePasswordToken) {
			String username = (String) authenticationToken.getPrincipal();
			User user = userMapper.selectUserByUsernameOrPhone(username);
			if (user == null) {
				// 用户名不存在
				throw new UnknownAccountException(GlobalConstants.USER_NOT_EXIST.getMessage());
			}
			// 校验密码通过后，返回认证信息
			return new SimpleAuthenticationInfo(user, user.getUserPassword(), ByteSource.Util.bytes(user.getUserSalt()), getName());
		}
		return null;
	}
}
